<template>
  <div >
    <!-- 注册 -->
    <div class="user-register-page">
      <div class="auth-group">
        <!-- 用户名 -->
        <div class="input-box">
          <div class="input-title">用户名</div>
          <el-input id="accounts" v-model="userName" placeholder="输入用户名" clearable></el-input>
        </div>

        <!-- 邮箱 -->
        <div class="input-box">
          <div class="input-title">邮箱</div>
          <el-autocomplete 
            type="email" 
            v-model="email" 
            placeholder="输入邮箱" 
            clearable 
            :fetch-suggestions="queryEamil"
            @blur="regEmail()" 
            @input="regEmail()"/>
        </div>

        <!-- 验证码 -->
        <div class="input-box">
          <div class="input-title">验证码</div>
          <el-input :disabled="!regEmailSuccess" v-model="smsCode" maxlength="4" placeholder="输入验证码">
            <el-button 
              :disabled="!regEmailSuccess || getCodeBtnCountDown" 
              slot="suffix" 
              type="primary" 
              size="mini" 
              plain 
              @click="getSmsCode"
              >{{getCodeBtnText}}</el-button>
          </el-input>
        </div>

        <!-- 密码 -->
        <div class="input-box">
          <div class="input-title">密码</div>
          <el-input 
            id="password"
            :disabled="email.length <= 0 || smsCode.length != 4" 
            v-model="password" 
            placeholder="设置密码" 
            show-password 
            clearable></el-input>
        </div>

        <!-- 头像 -->
        <div class="input-box">
          <div class="input-title">头像</div>
          <avatar :size="60" :src="userImage" v-if="invateCode"/>
          <div class="select-img">
            <input type="file" class="upload-file" @change="addImage($event)" accept=".jpg, .jpeg, .png, .gif"/>
            <el-button type="text" size="small" :loading="imageLoading">{{imageLoadingStr}}</el-button>
          </div>
        </div>
      </div>

      <!-- 注册、登录按钮 -->
      <div class="auth-group register-btn">
        <el-button type="primary" @click="register">立即注册</el-button>

        <span class="change-type">
          <span>已有账号？&nbsp; </span>
          <nuxt-link style="color : #409EFF" to="/userLogin">去登录</nuxt-link>
        </span>
      </div>
    </div>

    <!-- 邀请码 -->
    <invite-code @finish="finishinviteCode"/>
  </div>
</template>

<script>
import Api from "@/utils/api.js";
import Avatar from '@/components/Avatar.vue'
import InviteCode from './components/InviteCode.vue'
import OssUtils from "@/utils/ossUtils.js"
let interval;

export default {

  head(){
    return{
      title: `注册`,
      meta:[
        // 阻止搜索引擎编入索引
        { name:'robots',content: 'noindex'}
      ]
    }
  },

  components:{
    Avatar,
    InviteCode
  },

  data(){
    return{
      isInviteSuccess: false,
      invateCode:'',

      userName:'',
      email:'',
      smsCode:'',
      password:'',
      inviteCode:'',
      userAvatar: "",

      passwordEnalble: false,
      regEmailSuccess: false,

      getCodeBtnCountDown: false,
      getCodeBtnText:"立即获取",

      // 头像更换
      imageLoading: false,
      imageLoadingStr: "更换头像",

      userImage:"",
      avatarPop: false,
      avatarIndex: null,
      avatarList : [
        // "https://img.huiyong.online/userImage/avatar1.gif",
        // "https://img.huiyong.online/userImage/avatar2.gif",
        "https://img.huiyong.online/userImage/avatar4.gif",
        "https://img.huiyong.online/userImage/avatar6.gif",
        "https://img.huiyong.online/userImage/avatar7.gif",
        "https://img.huiyong.online/userImage/avatar8.gif",
        "https://img.huiyong.online/userImage/avatar9.gif",
      ],

      emailAllEnd:[
        {value : "@qq.com"},
        {value : "@163.com"},
        {value : "@sina.com"},
        {value : "@sina.cn"},
        {value : "@sohu.com"},
        {value : "@126.com"},
        {value : "@139.com"},
        {value : "@189.cn"},
        {value : "@outlook.com"},
        {value : "@hotmail.com"},
        {value : "@foxmail.com"},
        {value : "@21cn.com"},
        {value : "@aliyun.com"},
        {value : "@vip.163.com"},
        {value : "@vip.126.com"},
        {value : "@188.com"},
        {value : "@live.cn"},
        {value : "@gmail.com"},
        {value : "@yahoo.com"},
        {value : "@yeah.com"}
      ]
    }
  },

  mounted(){
    this.avatarIndex = Math.round(Math.random()* this.avatarList.length) - 1;
    this.userImage = this.avatarList[this.avatarIndex]
  },

  methods:{
    finishinviteCode(code){
      this.isInviteSuccess = true
      this.invateCode = code
    },

    selectImage(index){
      this.avatarIndex = index
      this.avatarPop = false
      this.userImage = this.avatarList[this.avatarIndex]
    },

    // 邮箱推荐
    queryEamil(queryString, callback) {
      let emailLeft="";
      let emailRight="";
      if(queryString.indexOf("@")>0){
        // 邮箱@左边的内容
        emailLeft = queryString.substring(0, queryString.indexOf("@"));
        // 邮箱@右边的内容
        emailRight = queryString.substring(queryString.indexOf("@"));
      }else{
        emailLeft = queryString;
      }

      // 调用 callback 返回建议列表的数据
      if(queryString){
        var results = JSON.parse(JSON.stringify(this.emailAllEnd))
        // 补充邮箱输入的内容
        results = results.map( item => {
          item.value = emailLeft + item.value
          return item
        })

        // 过滤符合格式的邮箱地址
        results = results.filter(item => (item.value.indexOf(emailRight) > 0 || !emailRight) && queryString != item.value )
        callback(results);
      }else{
        // 返回空选项
        callback([]);
      }     
    },

    //邮箱错误验证
    regEmail(){
      const reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
      this.regEmailSuccess = reg.test(this.email)
    },

    // 获取注册验证码
    getSmsCode(){
      this.getCodeBtnCountDown = true
      this.$axios.post(Api.SMS_REGISTER_CODE, {email: this.email}).then( _ =>{
        // 提示查收
        this.$message.success("已发送验证码，请查收！");
        // 验证码倒计时
        this.countDown(60)

      }).catch(res =>{
        // 初始化验证码获取按钮状态
        this.getCodeBtnCountDown = false
        // 提示失败
        this.$message.warning(res.message);
      })
    },

    // 验证码倒计时
    countDown(time){

      // 倒计时初始化
      clearInterval(this.interval)
      this.getCodeBtnText = time + "s"

      this.interval = setInterval(() => {
        if(time > 0){
          time --;
          this.getCodeBtnText = time + "s"
        }
        else{
          clearInterval(interval);
          this.getCodeBtnText = '重新获取';
          this.getCodeBtnCountDown = false;
        }
      }, 1000)
    },

    // 注册账号
    register(){
      if(!this.userName){
        this.$message.warning("请输入用户名!");
        return
      }
      
      this.$axios.post(Api.USER_REGISTER, {
        userName : this.userName,
        smsCode : this.smsCode,
        email: this.email,
        userImage: this.userImage,
        password : this.password,
        inviteCode : this.invateCode
      }).then( res =>{
        // 注册成功
        // 跳转后没有后退功能 
        window.location.replace('/')
      }).catch(res =>{
        // 提示失败
        this.$message.warning(res.message);
      })
    },

    addImage(event){
      if(event.target.files && event.target.files.length > 0){
        // 要上传的文件
        let imageFile = event.target.files[0]
        let key = "userImage/001/" + new Date().getTime() + imageFile.name; 
        OssUtils.upImage(this, key, imageFile, {
          error: res => { 
            this.imageLoading = false
            this.imageLoadingStr = "更换头像"
            this.$message.error(res);
          },
          
          success: _ => {
            this.imageLoading = false
            this.imageLoadingStr = "更换头像"

            this.userImage = "https://img.huiyong.online/" + key
          },
          
          progress: progress => {
            this.imageLoading = true
            this.imageLoadingStr = parseFloat(progress) * 100 + "%"
          }
        })
      }
    }
  }
}
</script>

<style lang="less">
@import './index.less';
</style>
